package com.ymy.thinking.in.spring.dependency.lookup;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * {@link ObjectProvider} 延迟依赖查找示例
 *
 * @author Ringo
 * @date 2021/8/31 11:31
 */
public class ObjectProviderDemo {

    public static void main(String[] args) {
        // 创建 IoC 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 包扫描
        applicationContext.scan("com.ymy.thinking.in.spring.dependency.lookup.**");

        // 开启 Spring 应用上下文
        applicationContext.refresh();

        // 通过 ObjectProvider 实现延迟依赖查找
        lookupByObjectProvider(applicationContext, String.class);

        // 关闭 Spring 应用上下文
        applicationContext.close();
    }

    private static <T> void lookupByObjectProvider(BeanFactory beanFactory, Class<T> requiredType) {
        ObjectProvider<T> objectProvider = beanFactory.getBeanProvider(requiredType);
        // 该方法来自于 ObjectFactory#getObject() 方法
        T object = objectProvider.getObject();
        System.out.println(object);
    }

    @Configuration
    public static class Config {

        @Bean
        @Primary
        public String hello() {
            return "Hello World";
        }
    }

}
